// 俄罗斯方块游戏逻辑

// 游戏状态变量
let canvas, ctx;
let board = [];
let currentPiece = null;
let nextPiece = null;
let score = 0;
let level = 1;
let linesCleared = 0;
let gameInterval;
let isGameRunning = false;
let startTime;
let elapsedTime = 0;
let timerInterval;
let gameDuration;

// 游戏配置
const COLS = 10;
const ROWS = 20;
const BLOCK_SIZE = 30;
const INITIAL_SPEED = 1000; // 初始下落速度（毫秒）

// 方块形状定义
const SHAPES = [
    // I型
    [
        [0, 0, 0, 0],
        [1, 1, 1, 1],
        [0, 0, 0, 0],
        [0, 0, 0, 0]
    ],
    // J型
    [
        [2, 0, 0],
        [2, 2, 2],
        [0, 0, 0]
    ],
    // L型
    [
        [0, 0, 3],
        [3, 3, 3],
        [0, 0, 0]
    ],
    // O型
    [
        [4, 4],
        [4, 4]
    ],
    // S型
    [
        [0, 5, 5],
        [5, 5, 0],
        [0, 0, 0]
    ],
    // T型
    [
        [0, 6, 0],
        [6, 6, 6],
        [0, 0, 0]
    ],
    // Z型
    [
        [7, 7, 0],
        [0, 7, 7],
        [0, 0, 0]
    ]
];

// 方块颜色
const COLORS = [
    null,        // 0: 空白
    '#00f',      // 1: I型 - 蓝色
    '#008',      // 2: J型 - 深蓝色
    '#f80',      // 3: L型 - 橙色
    '#ff0',      // 4: O型 - 黄色
    '#0f0',      // 5: S型 - 绿色
    '#80f',      // 6: T型 - 紫色
    '#f00'       // 7: Z型 - 红色
];

// 页面加载完成后初始化游戏
window.addEventListener('DOMContentLoaded', function() {
    initializeGame();
});

// 初始化游戏
function initializeGame() {
    // 获取画布和上下文
    canvas = document.getElementById('tetrisCanvas');
    ctx = canvas.getContext('2d');
    
    // 获取游戏设置
    const settings = getGameSettings();
    gameDuration = settings.gameDuration;
    
    // 显示最高分
    document.getElementById('highScore').textContent = getHighScore('tetris');
    
    // 初始化游戏板
    resetBoard();
    
    // 生成初始方块
    currentPiece = createPiece();
    nextPiece = createPiece();
    
    // 绘制初始游戏状态
    draw();
    
    // 添加事件监听器
    document.getElementById('startBtn').addEventListener('click', startGame);
    document.getElementById('pauseBtn').addEventListener('click', togglePause);
    document.getElementById('resetBtn').addEventListener('click', resetGame);
    
    // 添加键盘控制
    document.addEventListener('keydown', handleKeyPress);
}

// 重置游戏板
function resetBoard() {
    board = [];
    for (let r = 0; r < ROWS; r++) {
        board[r] = [];
        for (let c = 0; c < COLS; c++) {
            board[r][c] = 0;
        }
    }
    
    score = 0;
    level = 1;
    linesCleared = 0;
    elapsedTime = 0;
    
    // 更新显示
    document.getElementById('score').textContent = score;
    document.getElementById('level').textContent = level;
    document.getElementById('timer').textContent = formatTime(elapsedTime);
}

// 创建新方块
function createPiece() {
    const type = Math.floor(Math.random() * SHAPES.length);
    const shape = SHAPES[type];
    
    return {
        shape: shape,
        type: type + 1, // +1 因为颜色数组索引从1开始
        x: Math.floor((COLS - shape[0].length) / 2),
        y: 0
    };
}

// 开始游戏
function startGame() {
    if (isGameRunning) return;
    
    isGameRunning = true;
    startTime = Date.now() - elapsedTime * 1000;
    
    // 更新按钮状态
    document.getElementById('startBtn').disabled = true;
    document.getElementById('pauseBtn').disabled = false;
    
    // 启动游戏循环
    gameInterval = setInterval(gameLoop, calculateSpeed());
    
    // 启动计时器
    timerInterval = setInterval(updateTimer, 1000);
}

// 游戏主循环
function gameLoop() {
    // 尝试下移方块
    if (!movePiece(0, 1)) {
        // 方块不能下移，固定它
        lockPiece();
        
        // 检查是否有完整行
        const lines = checkLines();
        if (lines > 0) {
            clearLines(lines);
        }
        
        // 生成新方块
        currentPiece = nextPiece;
        nextPiece = createPiece();
        
        // 检查游戏是否结束
        if (checkGameOver()) {
            gameOver();
            return;
        }
    }
    
    // 绘制游戏
    draw();
}

// 移动方块
function movePiece(dx, dy, testOnly = false) {
    const newX = currentPiece.x + dx;
    const newY = currentPiece.y + dy;
    
    // 检查是否可以移动
    if (!checkCollision(currentPiece.shape, newX, newY)) {
        if (!testOnly) {
            currentPiece.x = newX;
            currentPiece.y = newY;
        }
        return true;
    }
    
    return false;
}

// 旋转方块
function rotatePiece(testOnly = false) {
    const newShape = [];
    const rows = currentPiece.shape.length;
    const cols = currentPiece.shape[0].length;
    
    // 创建旋转后的形状
    for (let r = 0; r < cols; r++) {
        newShape[r] = [];
        for (let c = 0; c < rows; c++) {
            newShape[r][c] = currentPiece.shape[rows - 1 - c][r];
        }
    }
    
    // 检查是否可以旋转
    if (!checkCollision(newShape, currentPiece.x, currentPiece.y)) {
        if (!testOnly) {
            currentPiece.shape = newShape;
        }
        return true;
    }
    
    // 尝试墙踢（wall kick）
    const kicks = [{x: -1, y: 0}, {x: 1, y: 0}, {x: -2, y: 0}, {x: 2, y: 0}];
    for (let kick of kicks) {
        if (!checkCollision(newShape, currentPiece.x + kick.x, currentPiece.y + kick.y)) {
            if (!testOnly) {
                currentPiece.shape = newShape;
                currentPiece.x += kick.x;
            }
            return true;
        }
    }
    
    return false;
}

// 检查碰撞
function checkCollision(shape, x, y) {
    for (let r = 0; r < shape.length; r++) {
        for (let c = 0; c < shape[r].length; c++) {
            if (shape[r][c] !== 0) {
                const boardX = x + c;
                const boardY = y + r;
                
                // 检查边界
                if (boardX < 0 || boardX >= COLS || boardY >= ROWS) {
                    return true;
                }
                
                // 检查与已有方块的碰撞
                if (boardY >= 0 && board[boardY][boardX] !== 0) {
                    return true;
                }
            }
        }
    }
    
    return false;
}

// 固定方块到游戏板
function lockPiece() {
    for (let r = 0; r < currentPiece.shape.length; r++) {
        for (let c = 0; c < currentPiece.shape[r].length; c++) {
            if (currentPiece.shape[r][c] !== 0) {
                const boardX = currentPiece.x + c;
                const boardY = currentPiece.y + r;
                
                if (boardY >= 0) {
                    board[boardY][boardX] = currentPiece.type;
                }
            }
        }
    }
}

// 检查是否有完整的行
function checkLines() {
    let lines = 0;
    
    for (let r = ROWS - 1; r >= 0; r--) {
        let isComplete = true;
        
        for (let c = 0; c < COLS; c++) {
            if (board[r][c] === 0) {
                isComplete = false;
                break;
            }
        }
        
        if (isComplete) {
            lines++;
        }
    }
    
    return lines;
}

// 消除完整的行
function clearLines(lines) {
    // 计算得分
    const linePoints = [0, 100, 300, 500, 800]; // 1-4行的得分
    score += linePoints[lines] * level;
    linesCleared += lines;
    
    // 检查是否升级
    if (linesCleared >= level * 10) {
        level++;
        // 加快游戏速度
        clearInterval(gameInterval);
        gameInterval = setInterval(gameLoop, calculateSpeed());
    }
    
    // 更新显示
    document.getElementById('score').textContent = score;
    document.getElementById('level').textContent = level;
    
    // 实际消除行
    for (let r = ROWS - 1; r >= 0; r--) {
        let isComplete = true;
        
        for (let c = 0; c < COLS; c++) {
            if (board[r][c] === 0) {
                isComplete = false;
                break;
            }
        }
        
        if (isComplete) {
            // 移除当前行
            board.splice(r, 1);
            // 在顶部添加新的空行
            board.unshift(new Array(COLS).fill(0));
            // 因为移除了一行，需要重新检查当前位置
            r++;
        }
    }
}

// 检查游戏是否结束
function checkGameOver() {
    return checkCollision(currentPiece.shape, currentPiece.x, currentPiece.y);
}

// 计算游戏速度
function calculateSpeed() {
    return Math.max(INITIAL_SPEED - (level - 1) * 100, 100);
}

// 更新计时器
function updateTimer() {
    elapsedTime = Math.floor((Date.now() - startTime) / 1000);
    document.getElementById('timer').textContent = formatTime(elapsedTime);
    
    // 检查游戏时间是否结束
    if (gameDuration > 0 && elapsedTime >= gameDuration) {
        gameOver();
    }
}

// 绘制游戏
function draw() {
    // 清空画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 绘制游戏板
    for (let r = 0; r < ROWS; r++) {
        for (let c = 0; c < COLS; c++) {
            if (board[r][c] !== 0) {
                drawBlock(c, r, board[r][c]);
            }
        }
    }
    
    // 绘制当前方块
    if (currentPiece) {
        for (let r = 0; r < currentPiece.shape.length; r++) {
            for (let c = 0; c < currentPiece.shape[r].length; c++) {
                if (currentPiece.shape[r][c] !== 0) {
                    const boardX = currentPiece.x + c;
                    const boardY = currentPiece.y + r;
                    
                    if (boardY >= 0) {
                        drawBlock(boardX, boardY, currentPiece.shape[r][c]);
                    }
                }
            }
        }
    }
    
    // 绘制网格线
    drawGrid();
}

// 绘制单个方块
function drawBlock(x, y, type) {
    ctx.fillStyle = COLORS[type];
    ctx.fillRect(x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);
    
    // 绘制边框
    ctx.strokeStyle = '#fff';
    ctx.lineWidth = 1;
    ctx.strokeRect(x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);
    
    // 绘制内部阴影效果
    ctx.fillStyle = 'rgba(255, 255, 255, 0.3)';
    ctx.fillRect(x * BLOCK_SIZE + 2, y * BLOCK_SIZE + 2, BLOCK_SIZE - 4, BLOCK_SIZE / 2 - 2);
    
    ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
    ctx.fillRect(x * BLOCK_SIZE + 2, y * BLOCK_SIZE + BLOCK_SIZE / 2, BLOCK_SIZE - 4, BLOCK_SIZE / 2 - 2);
}

// 绘制网格线
function drawGrid() {
    ctx.strokeStyle = '#333';
    ctx.lineWidth = 0.5;
    
    // 绘制垂直线
    for (let c = 0; c <= COLS; c++) {
        ctx.beginPath();
        ctx.moveTo(c * BLOCK_SIZE, 0);
        ctx.lineTo(c * BLOCK_SIZE, canvas.height);
        ctx.stroke();
    }
    
    // 绘制水平线
    for (let r = 0; r <= ROWS; r++) {
        ctx.beginPath();
        ctx.moveTo(0, r * BLOCK_SIZE);
        ctx.lineTo(canvas.width, r * BLOCK_SIZE);
        ctx.stroke();
    }
}

// 切换暂停状态
function togglePause() {
    if (isGameRunning) {
        pauseGame();
    } else {
        resumeGame();
    }
}

// 暂停游戏
function pauseGame() {
    clearInterval(gameInterval);
    clearInterval(timerInterval);
    isGameRunning = false;
    document.getElementById('pauseBtn').textContent = '继续';
}

// 继续游戏
function resumeGame() {
    startTime = Date.now() - elapsedTime * 1000;
    gameInterval = setInterval(gameLoop, calculateSpeed());
    timerInterval = setInterval(updateTimer, 1000);
    isGameRunning = true;
    document.getElementById('pauseBtn').textContent = '暂停';
}

// 快速下落到底部
function hardDrop() {
    while (movePiece(0, 1)) {
        // 持续下移直到不能移动
    }
    
    // 立即进入下一个方块
    lockPiece();
    
    const lines = checkLines();
    if (lines > 0) {
        clearLines(lines);
    }
    
    currentPiece = nextPiece;
    nextPiece = createPiece();
    
    if (checkGameOver()) {
        gameOver();
        return;
    }
    
    draw();
}

// 游戏结束
function gameOver() {
    clearInterval(gameInterval);
    clearInterval(timerInterval);
    isGameRunning = false;
    
    document.getElementById('startBtn').disabled = false;
    document.getElementById('pauseBtn').disabled = true;
    document.getElementById('pauseBtn').textContent = '暂停';
    
    // 记录分数
    recordScore('tetris', score, elapsedTime);
    
    // 更新最高分
    document.getElementById('highScore').textContent = getHighScore('tetris');
    
    // 显示游戏结束消息
    showMessage(`游戏结束！得分：${score}，等级：${level}，用时：${formatTime(elapsedTime)}`, 'warning');
}

// 重置游戏
function resetGame() {
    clearInterval(gameInterval);
    clearInterval(timerInterval);
    isGameRunning = false;
    
    document.getElementById('startBtn').disabled = false;
    document.getElementById('pauseBtn').disabled = true;
    document.getElementById('pauseBtn').textContent = '暂停';
    
    resetBoard();
    
    currentPiece = createPiece();
    nextPiece = createPiece();
    
    draw();
}

// 处理键盘输入
function handleKeyPress(e) {
    // 防止页面滚动
    if ([37, 38, 39, 40, 32].includes(e.keyCode)) {
        e.preventDefault();
    }
    
    if (!isGameRunning) return;
    
    switch (e.keyCode) {
        case 37: // 左箭头
        case 65: // A键
            movePiece(-1, 0);
            break;
        case 39: // 右箭头
        case 68: // D键
            movePiece(1, 0);
            break;
        case 40: // 下箭头
        case 83: // S键
            movePiece(0, 1);
            // 加快下落时给予额外分数
            score += 1;
            document.getElementById('score').textContent = score;
            break;
        case 38: // 上箭头
        case 87: // W键
            rotatePiece();
            break;
        case 32: // 空格键
            hardDrop();
            // 硬降落给予额外分数
            score += 2;
            document.getElementById('score').textContent = score;
            break;
        case 80: // P键
            togglePause();
            break;
        case 82: // R键
            resetGame();
            break;
    }
    
    draw();
}